from flask import current_app, jsonify
from flask import g

from info import constants, db
from info.models import User, News
from info.modules.news import news_blue
from info.utils.common import get_login_info
from info.utils.response_code import RET

from flask import render_template


@news_blue.route('/<int:news_id>')
@get_login_info
def news_index(news_id):
    user = g.user
    news_list = None
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)
    click_news_list = []
    for news in news_list if news_list else []:
        click_news_list.append(news.to_basic_dict())
    # 查找新闻
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='查找新闻失败')
    if not news:
        return jsonify(errno=RET.DATAERR, errmsg='查找新闻失败')
    news.clicks += 1
    try:
        db.commit()
    except Exception as e:
        db.session.rollback()
    # 判断是否收藏
    collected = False
    if user:
        if news in user.collection_news:
            collected = True

    data = {
        'user_info': user.to_dict() if user else None,
        'click_news_list': click_news_list,
        'news': news.to_dict(),
        'is_collected': collected}
    return render_template('news/detail.html', data=data)
